package axht.trade.android.storage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InnerActivity extends AppCompatActivity {


    private ImageView imageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inner);
        imageView = findViewById(R.id.imageView);
    }

    /**
     * 将assets图片保存到手机内部
     *
     * @param view
     */
    public void saveImage(View view) throws IOException {
        InputStream logoImageInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //1 获取assetManager
            AssetManager assetManager = getAssets();
            logoImageInputStream = assetManager.open("logo.png");
            //2 获取手机内部文件
            File filesDir = getFilesDir();
            String filesDirPath = filesDir.getAbsolutePath();
            String filePath = filesDirPath + "/logo.png";
            fileOutputStream = new FileOutputStream(filePath);
            byte[] bytes = new byte[1024];
            while (logoImageInputStream.read(bytes) != -1) {
                fileOutputStream.write(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭输入输出流
            if (fileOutputStream!=null){
                fileOutputStream.flush();
                fileOutputStream.close();
            }
            if(logoImageInputStream!=null){
                logoImageInputStream.close();
            }
        }
    }

    /**
     * 读取手机内部图片显示到ImageView
     *
     * @param view
     */
    public void readImage(View view) {
        // 1 获取手机内部文件
        File filesDir = getFilesDir();
        String filesDirAbsolutePath = filesDir.getAbsolutePath();
        String imagePath = filesDirAbsolutePath+"/logo.png";
        // 2 加载图片
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        imageView.setImageBitmap(bitmap);

    }
}
